package handler

import (
	"github.com/gin-gonic/gin"
	"golang-websocket-chatroom/pkg"
	"golang-websocket-chatroom/pkg/jwt"
	"golang-websocket-chatroom/repository"
	"golang-websocket-chatroom/request"
	"golang-websocket-chatroom/response"
)

const JWT_USER_ID = "2210a"

func Login(c *gin.Context) {
	var data request.LoginUser
	err := c.ShouldBind(&data)
	if err != nil {
		response.ResponseError(c, "错误", err.Error())
		return
	}
	login, err := repository.Login(data.Name)
	if login.Id == 0 {
		response.ResponseError(c, "用户不存在", err)
		return
	}
	if login.Password != pkg.Md5(data.Password) {
		response.ResponseError(c, "密码错误", err)
		return
	}
	claims := jwt.CustomClaims{ID: login.Id}
	token, err := jwt.NewJWT(JWT_USER_ID).CreateToken(claims)
	if err != nil {
		response.ResponseError(c, "token生成失败", err)

		return
	}
	response.ResponseSuccess(c, "登陆成功", token)
}
